package com.gzy.blog.blog.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.gzy.blog.blog.dao.ArticleDao;
import com.gzy.blog.blog.entity.Article;
import com.gzy.blog.common.BaseDao;
import com.gzy.blog.common.PageModel;

@Repository
public class ArticleDaoImpl extends BaseDao<Article, Integer> implements ArticleDao {

	@Override
	public PageModel<Article> pageArticle(int pageNo, int pageSize) {
		// TODO Auto-generated method stub ORDER BY a.createTime DESC
		String hql = "SELECT new Article(a.id,a.title,u.id,a.content,a.createTime,a.readTimes,u.photo,u.username,c.name) FROM Article a,User u,Category c WHERE u.id=a.userId AND a.categoryId=c.id ORDER BY a.createTime DESC";
		// String hql = "FROM Article";
		return pageEntityByHql(pageNo, pageSize, hql);
	}

	@Override
	public List<Article> listWellArticle() {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM article ORDER BY read_times DESC limit 0,10";
		return listEntityBySql(sql);
	}

	@Override
	public PageModel<Article> getArticlePageByUserId(Integer userId) {
		// 进入个人博客 遍历的个人 文章
		String hql = "SELECT new Article(a.id,a.title,a.content,a.createTime,a.readTimes,c.name,a.userId)FROM Article a,Category c WHERE a.userId="
				+ userId;
		return pageEntityByHql(1, 10, hql);
	}

	@Override
	public Article getArticleById(Integer id) {
		// TODO Auto-generated method stub
		String hql = "select new Article(a.id,a.title,a.content,a.createTime,a.readTimes,c.name,a.userId) FROM Article a,Category c WHERE a.id="
				+ id;
		return uniqueEntityByHql(hql);
	}

	@Override
	public List<Article> listWellAticleSelf(Integer userId) {
		String sql = "SELECT * FROM article WHERE user_id=? ORDER BY read_times DESC limit 0,10";
		return listEntityBySql(sql, userId);
	}

	@Override
	public List<Article> listArticleCategory(Integer userId) {
		// TODO Auto-generated method stub
		// String hql =
		// "SELECT new Article(count(a.categoryId),c.name) FROM Article
		// a,Category c WHERE a.userId=? AND a.userId=c.userId GROUP BY
		// a.categoryId";
		String sql = "SELECT count(*),c.name FROM article a,category c WHERE a.category_id=c.id AND a.user_id=? GROUP BY category_id";
		// return listEntityByHql(hql, userId);
		List<Article> la = new ArrayList();
		List<Object[]> sb = listMultiPropertyBySql(sql, userId);
		for (Object[] objects : sb) {
			Article a = new Article();
			a.setCategorySum(((Number) objects[0]).intValue());
			a.setCategoryName((String) objects[1]);
			la.add(a);
		}
		return la;
	}

	@Override
	public void add(Article article) {
		// TODO Auto-generated method stub
		article.setCreateTime(new Date());
		save(article);
	}

	@Override
	public void delete(Integer id) {
		// TODO Auto-generated method stub
		Article article = get(id);
		delete(article);
	}
}
